package com.woniuxy.project115.kaer.user.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class RabbitMQConfig {
    //创建保存发送注册验证码的手机号的队列
    @Bean
    public Queue regCodeQueue(){
        return new Queue("send_reg_code_queue");
    }
    //定义路由模式下的交换机
    @Bean
    public DirectExchange d1(){
        return new DirectExchange("d1");
    }
    //创建延迟队列中没有过期时间的队列
    @Bean
    public Queue deleteCacheQueue(){
        return new Queue("delete_cache_queue");
    }
    //交换机和路由键的绑定
    @Bean
    public Binding bdDeleteCacheQueueToD1(){
        return BindingBuilder.bind(deleteCacheQueue()).to(d1()).with("delete_cache");
    }
    //创建有过期时间的队列
    @Bean
    public Queue waitingDeleteCacheQueue(){
        HashMap<String, Object> params = new HashMap<>();
        //定义该队列中消息的生存时间 单位毫秒 生存时间最终对应业务的延迟执行时间
        params.put("x-message-ttl", 5 * 1000);
        // x-dead-letter-exchange 属性用于声明死信转发到的交换机
        params.put("x-dead-letter-exchange", "d1");
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的路由键名称。
        params.put("x-dead-letter-routing-key", "delete_cache");
        return new Queue("waiting_delete_cache_queue", true, false, false, params);
    }
    //创建延迟删除长token的队列
    @Bean
    public Queue deleteTokenQueue(){
        return new Queue("delete_token_queue");
    }

//    //有过期时间的队列
//    @Bean
//    public Queue waitingCheckOrderQueue(){
//        HashMap<String, Object> params = new HashMap<>();
//        //定义该队列中消息的生存时间 单位毫秒 生存时间最终对应业务的延迟执行时间
//        params.put("x-message-ttl",15 * 60 * 1000);
//        // x-dead-letter-exchange 属性用于声明死信转发到的交换机
//        params.put("x-dead-letter-exchange", "d1");
//        // x-dead-letter-routing-key 声明了这些死信在转发时携带的路由键名称。
//        params.put("x-dead-letter-routing-key", "check_order");
//        return new Queue("waiting_check_order_queue", true, false, false, params);
//    }

    @Bean
    public DirectExchange errorExchange(){
        return new DirectExchange("error-ex");
    }
    @Bean
    public Queue errorMessageQueue(){
        return new Queue("errorMessageQueue",true);
    }
    @Bean
    public Binding bindingErrorExchange(){
        return BindingBuilder.bind(errorMessageQueue()).to(errorExchange()).with("error");
    }

    @Bean
    public MessageRecoverer messageRecoverer(RabbitTemplate rabbitTemplate) {
        // 需要配置交换机和绑定键
        return new RepublishMessageRecoverer(rabbitTemplate, "error-ex", "error");
    }
}
